package com.tff.gmall.cart.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.tff.gmall.annotations.LoginRequired;
import com.tff.gmall.beans.OmsCartItem;
import com.tff.gmall.beans.PmsSkuInfo;
import com.tff.gmall.service.CartService;
import com.tff.gmall.service.PmsSkuInfoService;
import com.tff.gmall.util.CookieUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Fafa Tuo
 * @version 1.0
 * @date 2021/7/5 20:21
 */
@Controller
public class CartController {

    @Reference
    private PmsSkuInfoService pmsSkuInfoService;
    @Reference
    private CartService cartService;

    @RequestMapping(value = "/toTrade")
    @LoginRequired(logSuccess = true)
    public String toTrade(String skuId, String isChecked,
                          HttpServletRequest request,
                          HttpServletResponse response,
                          ModelMap modelMap) {

       String memberId = (String) request.getAttribute("memberId");
       String nickname = (String) request.getAttribute("nickname");

        return "toTrade";

    }


    @RequestMapping(value = "/checkCart")
    @LoginRequired(logSuccess = false)
    public String checkCart(String skuId, String isChecked,
                            HttpServletRequest request,
                            HttpServletResponse response,
                            ModelMap modelMap) {

        String memberId = (String) request.getAttribute("memberId");
        String nickname = (String) request.getAttribute("nickname");
        OmsCartItem omsCartItem = new OmsCartItem();
        omsCartItem.setMemberId(memberId);
        omsCartItem.setProductSkuId(skuId);
        omsCartItem.setCheck(isChecked);
        //调用服务，修改状态
        cartService.checkCart(omsCartItem);
        //将最新的数据从缓存中查出渲染给内嵌页
        List<OmsCartItem> cartList = cartService.getCartList(memberId);
        modelMap.put("cartList", cartList);
        //被勾选的商品的总额
        BigDecimal totalAmount = getTotalAmount(cartList);
        modelMap.put("totalAmount", totalAmount);
        return "cartListInner";
    }

    @RequestMapping(value = "/cartList")
    @LoginRequired(logSuccess = false)
    public String cartList(HttpServletRequest request,
                           HttpServletResponse response,
                           ModelMap modelMap) {
        List<OmsCartItem> omsCartItems = new ArrayList<>();

        String memberId = (String) request.getAttribute("memberId");
        String nickname = (String) request.getAttribute("nickname");
        if (StringUtils.isNotBlank(memberId)) {
            //查询当前用户服务器购物车中的数据（已经登录）
            omsCartItems = cartService.getCartList(memberId);
        } else {
            //查询当前浏览器端cookie中的数据（没有登录）
            String cartListCookie = CookieUtil.getCookieValue(request, "cartListCookie", true);
            System.out.println("=============caer==" + cartListCookie);
            if (StringUtils.isNotBlank(cartListCookie)) {
                omsCartItems = JSON.parseArray(cartListCookie, OmsCartItem.class);
            }
        }
        /*//金融或者钱的计算尽量使用BigDecimal
        for (OmsCartItem oms : omsCartItems) {
            oms.setTotalPrice(oms.getPrice().multiply(new BigDecimal(oms.getQuantity())));
        }*/
        modelMap.put("cartList", omsCartItems);
        //被勾选的商品的总额
        BigDecimal totalAmount = getTotalAmount(omsCartItems);
        modelMap.put("totalAmount", totalAmount);
        return "cartList";
    }

    private BigDecimal getTotalAmount(List<OmsCartItem> omsCartItems) {

        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsCartItem oms : omsCartItems) {
            BigDecimal totalPrice = oms.getTotalPrice();
            if (oms.getCheck().equals("1")) {
                totalAmount = totalAmount.add(totalPrice);
            }
        }
        return totalAmount;
    }

    @RequestMapping(value = "/addToCart")
    @LoginRequired(logSuccess = false)
    public String addToCart(String skuId, Integer quantity, HttpServletRequest request, HttpServletResponse response) {
        List<OmsCartItem> omsCartItems = new ArrayList<OmsCartItem>();
        quantity = 1;
        //调用商品服务查询商品信息
        PmsSkuInfo pmsSkuInfo = pmsSkuInfoService.getPmsSkuInfoBySkuId(skuId, "");
        //将商品信息封装成购物车信息
        OmsCartItem omsCartItem = new OmsCartItem();
        omsCartItem.setProductSkuId(pmsSkuInfo.getId());
        omsCartItem.setCreateDate(new Date());
        omsCartItem.setDeleteStatus(0);
        omsCartItem.setPrice(pmsSkuInfo.getPrice());
        omsCartItem.setModifyDate(new Date());
        omsCartItem.setProductCategoryId(pmsSkuInfo.getCatalog3Id());
        omsCartItem.setProductId(pmsSkuInfo.getProductId());
        omsCartItem.setProductBrand("肥仔子");
        omsCartItem.setQuantity(quantity);
        omsCartItem.setProductSkuCode("999999999999");
        omsCartItem.setProductPic(pmsSkuInfo.getSkuDefaultImg());
        omsCartItem.setProductName(pmsSkuInfo.getSkuName());
        //判断用户是否登录
        String memberId = (String) request.getAttribute("memberId");
        String nickname = (String) request.getAttribute("nickname");

        //根据用胡的状态决定是缓存还是写库
        if (StringUtils.isNotBlank(memberId)) {
            //写库，用户登录
            //查询用户是否在购物车中添加过当前的商品
            OmsCartItem omsCartItemFromDb = cartService.ifCartExitsByUser(memberId, skuId);
            if (omsCartItemFromDb == null) {
                //db空
                omsCartItem.setMemberId(memberId);
                omsCartItem.setQuantity(quantity);
                omsCartItem.setMemberNickname("test小发");
                cartService.addToCart(omsCartItem);
            } else {
                //db不为空
                omsCartItemFromDb.setQuantity(omsCartItem.getQuantity() + omsCartItemFromDb.getQuantity());
                cartService.updateToCart(omsCartItemFromDb);
            }

            //同步缓存
            cartService.flushCartCache(memberId);

        } else {
            //写cookie缓存，用户没有登录
            //cookie里原有的购物车数据
            String cartListCookie = CookieUtil.getCookieValue(request, "cartListCookie", true);
            //添加之前，我需要先判断cookie中到底有没有数据
            if (StringUtils.isBlank(cartListCookie)) {
                //cookie为空
                omsCartItems.add(omsCartItem);
            } else {
                omsCartItems = JSON.parseArray(cartListCookie, OmsCartItem.class);
                //cookie不为空
                boolean exist = ifCartExits(omsCartItem, omsCartItems);
                if (exist) {
                    //现在添加的sku在之前的购物车中存在，更新购物车中的数量
                    for (OmsCartItem cartItem : omsCartItems) {
                        if (cartItem.getProductSkuId().equals(omsCartItem.getProductSkuId())) {
                            cartItem.setQuantity(cartItem.getQuantity() + omsCartItem.getQuantity());
                            //cartItem.setPrice(cartItem.getPrice().add(omsCartItem.getPrice()));
                        }
                    }
                } else {
                    //否则，不存在，添加购物车
                    omsCartItems.add(omsCartItem);
                }
            }
            System.out.println("开始写cookie");
            CookieUtil.setCookie(request, response, "cartListCookie", JSON.toJSONString(omsCartItems), 60 * 60 * 72, true);
        }
        return "redirect:/success.html";
    }

    private boolean ifCartExits(OmsCartItem omsCartItem, List<OmsCartItem> omsCartItems) {
        boolean b = false;
        for (OmsCartItem om : omsCartItems) {
            String productSkuId = om.getProductSkuId();
            if (omsCartItem.getProductSkuId().equals(productSkuId)) {
                b = true;
                break;
            }
        }
        return b;
    }
}
